package com.redstar.HappyRefresh.audit;

import com.qiniu.http.Client;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.util.StringMap;
import com.redstar.HappyRefresh.config.QiNiuConfig;
import com.redstar.HappyRefresh.constant.AuditStatus;
import com.redstar.HappyRefresh.json.*;
import com.redstar.HappyRefresh.pojo.Setting;
import com.redstar.HappyRefresh.response.AuditResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ImageAuditService extends AbstractAuditService<String, AuditResponse>{ // 图片审核

    private static final String imageUlr = "http://ai.qiniuapi.com/v3/image/censor";
    private static final  String imageBody = "{\n" +
            "    \"data\": {\n" +
            "        \"uri\": \"${url}\"\n" +
            "    },\n" +
            "    \"params\": {\n" +
            "        \"scenes\": [\n" +
            "            \"pulp\",\n" +
            "            \"terror\",\n" +
            "            \"politician\"\n" +
            "        ]\n" +
            "    }\n" +
            "}";

    @Override
    public AuditResponse audit(String url) {
        // 封装视频审核返回的结果
        AuditResponse auditResponse = new AuditResponse();
        // 先标记为通过
        auditResponse.setAuditStatus(AuditStatus.SUCCESS);
        // 不需要审核直接返回
        if (!isNeedAudit()) {
            return auditResponse;
        }
        try {
            // url不包含自定义域名说明url有误，需重构
            if(!url.contains(QiNiuConfig.CNAME)) {
                String encodedFileName = URLEncoder.encode(url, "utf-8").replace("+", "%20");
                url = String.format("%s/%s", QiNiuConfig.CNAME, encodedFileName);
            }
            // 为url追加uuid字符串，拼接在url后面，并记录在本地缓存LocalCache中，用来标记这次文件审核
            url = appendUUID(url);
            // 替换imageBody中的${url}
            String body = imageBody.replace("${url}", url);
            String method = "POST";
            // 生成签名Token，用于发送HTTP请求
            String token = qiNiuConfig.getToken(imageUlr, method, body, contentType);
            // 七牛云自定义
            StringMap header = new StringMap();
            header.put("Host", "ai.qiniuapi.com");
            header.put("Authorization", token);
            header.put("Content-Type", contentType);
            // 华南地区region2已修改为华东地区region0，与其他为位置保持一致
            Configuration cfg = new Configuration(Region.region0());
            Client client = new Client(cfg);
            Response response = client.post(imageUlr, body.getBytes(), header, contentType);
            // 将结果转化为Map
            Map map = objectMapper.readValue(response.getInfo().split(" \n")[2], Map.class);
            // 将Map中的数据进行拆分
            ResultChildJson result = objectMapper.convertValue(map.get("result"), ResultChildJson.class);
            BodyJson bodyJson = new BodyJson();
            ResultJson resultJson = new ResultJson();
            resultJson.setResult(result);
            bodyJson.setResult(resultJson);
            Setting setting = settingService.getById(1);
            SettingScoreJson settingScoreRule = objectMapper.readValue(setting.getAuditPolicy(), SettingScoreJson.class);
            // 审核
            auditResponse = audit(settingScoreRule.getManualScore(), bodyJson);
            return auditResponse;
        } catch (Exception e) {
            // 出现异常为什么要设置为审核成功，应设置为审核失败
            auditResponse.setAuditStatus(AuditStatus.SUCCESS);
           log.error(e.getMessage(), e);
        }
        return auditResponse;
    }
}
